import React, { useContext, useState } from 'react'
import classNames from 'classnames'
import { MenuItemProps } from './menuItem'
import { MenuContext } from './menu'
import Icon from '../icon/index'
import Transition from '../transition/transition'
export interface SubMenuPops {
    index?: string;
    title: string;
    className?: string
}

const SubMenu: React.FC<SubMenuPops> = ({ index, title, className, children }) => {
    const context = useContext(MenuContext)
    const classes = classNames('menu-item submenu-item', className, {
        'is-active': context.index === index
    })
    // state 
    const [menuOpen, setmenuOpen] = useState(false)
    // 点击时间 根据不同模式决定用那种
    const handClick = (e: React.MouseEvent) => {
        e.preventDefault()
        setmenuOpen(!menuOpen)
    }
    let timer: any
    const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
        clearTimeout(timer)
        e.preventDefault()
        timer = setTimeout(() => {
            setmenuOpen(!menuOpen)
        }, 300);
    }
    const clickEvents = context.mode === 'vertical' ? {
        onClick: handClick
    } : {}
    const hoverEvents = context.mode !== 'vertical' ? {
        onMouseEnter: (e: React.MouseEvent) => { handleMouse(e, true) },
        onMouseLeave: (e: React.MouseEvent) => { handleMouse(e, false) }
    } : {}
    const renderChildren = () => {
        // 子选项样式 
        const subMenuClass = classNames('viking-submenu', {
            'menu-opened': menuOpen
        })
        const childrenComponent = React.Children.map(children, (child, i) => {
            const childrenElement = child as React.FunctionComponentElement<MenuItemProps>
            const { displayName } = childrenElement.type
            if (displayName === 'MenuItem') {
                // return child
                return React.cloneElement(childrenElement, { index: `${index}-${i}` })
            } else {
                console.log('请输入MenuItem');
            }
        })
        return (
            <Transition in={menuOpen} timeout={300} classNames='zoom-in-left'>
                <ul className={subMenuClass}>
                    {childrenComponent}
                </ul>
            </Transition>
        )
    }
    return (
        <li key={index} className={classes} {...hoverEvents}>
            <div className='submenu-title' {...clickEvents}>
                {title}
                <Icon icon='angle-down' className="arrow-icon" />
            </div>
            {renderChildren()}
        </li>
    )
}
SubMenu.displayName = 'SubMenu'

export default SubMenu